<script setup lang="ts">
import { reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryDataList, delDataList } from '@/api/develop/list'
import { useAppStore } from '@/store/modules/app'
import { useI18n } from '@/hooks/web/useI18n'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import { Paging } from '@/config/public'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useRouter } from 'vue-router'
import { selectModule } from '@/api/develop'
import { ModuleTree } from '@/components/Tree'

defineOptions({
  name: 'ListManage'
})

const appStore = useAppStore()
const { t } = useI18n()
const { push, currentRoute } = useRouter()
const localeStore = useLocaleStoreWithOut()
const curLang = localeStore.getCurrentLocale.lang

const state = reactive({
  searchKey: '',
  // 表格數據
  tableView: [{}],
  // 分頁相關屬性
  totalCount: 0,
  pageSizes: Paging.sizes,
  queryBody: {
    key: '',
    pageNo: 1,
    pageSize: Paging.defaultSize,
    params: {
      'Q_d.status_I_LT': 4
    },
    sortField: '',
    sortOrder: ''
  },
  listTypes: [
    {
      value: 0,
      icon: 'mdi:table-large',
      label: t('dataList.type0'),
      class: 'typeSelected',
      desc: t('dataList.typeDesc0')
    },
    {
      value: 1,
      icon: 'gg:notes',
      label: t('dataList.type1'),
      class: 'typeNormal',
      desc: t('dataList.typeDesc1')
    },
    {
      value: 2,
      icon: 'solar:album-linear',
      label: t('dataList.type2'),
      class: 'typeNormal',
      desc: t('dataList.typeDesc2')
    },
    {
      value: 6,
      icon: 'mdi:chart-bar',
      label: t('dataList.type6'),
      class: 'typeNormal',
      desc: t('dataList.typeDesc6')
    },
    {
      value: 7,
      icon: 'mdi:chart-gantt',
      label: t('dataList.type7'),
      class: 'typeNormal',
      desc: t('dataList.typeDesc7')
    },
    {
      value: 8,
      icon: 'fluent-emoji-high-contrast:spiral-calendar',
      label: t('dataList.type8'),
      class: 'typeNormal',
      desc: t('dataList.typeDesc8')
    },
    {
      value: 3,
      icon: 'uis:window-maximize',
      label: t('dataList.type3'),
      class: 'typeNormal',
      desc: t('dataList.typeDesc3')
    },
    {
      value: 4,
      icon: 'vaadin:tree-table',
      label: t('dataList.type4'),
      class: 'typeNormal',
      desc: t('dataList.typeDesc4')
    },
    {
      value: 5,
      icon: 'icomoon-free:menu',
      label: t('dataList.type5'),
      class: 'typeNormal',
      desc: t('dataList.typeDesc5')
    }
  ],
  newTypeValue: 0,
  dialogVisible: false,
  dialogForm: { type: 0, entId: '' },
  dataListField: 'name',
  modNameField: 'moduleName',
  entNameField: 'entName',
  formNameField: 'fmName',
  moduleList: [{} as any],
  curModuleId: '',
  dsList: [{} as any]
})
onMounted(async () => {
  if (curLang == 'en') {
    state.dataListField = 'enName'
    state.modNameField = 'enModuleName'
    state.entNameField = 'enName'
    state.formNameField = 'enName'
  } else if (curLang == 'zh_HK') {
    state.dataListField = 'hkName'
    state.modNameField = 'hkModuleName'
    state.entNameField = 'hkName'
    state.formNameField = 'hkName'
  }
  state.moduleList = await selectModule()
  init()
})

const changePage = (page) => {
  state.queryBody.pageNo = page
  init()
}
const changePageSize = (pageSize) => {
  state.queryBody.pageSize = pageSize
  state.queryBody.pageNo = 1
  init()
}
// 刪除当前记录
const deleteOne = (row) => {
  ElMessageBox.confirm(t('common.delMessage'), t('common.warning'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await delDataList(row.id)
      init()
    })
    .catch(() => {})
}

// 修改
const edit = (id, type) => {
  if (type == 0) {
    push({
      name: 'ListEdit',
      query: {
        id: id
      }
    })
  } else {
    ElMessage.warning('该类型列表还没开发完成，敬请期待！')
  }
}

//预览数据列表
const preview = (id) => {
  push({
    name: 'ListShow',
    query: {
      listId: id,
      preview: 1,
      fromPath: currentRoute.value.fullPath
    }
  })
}

// 发布到菜单
const add2Menu = (row) => {
  push({
    name: 'MenuEdit',
    query: {
      id: null,
      type: 'list',
      listId: row.id,
      name: row.name,
      hkName: row.hkName,
      enName: row.enName,
      fromPath: currentRoute.value.fullPath
    }
  })
}

//点击类型时，切换样式
const clickListType = (value) => {
  state.newTypeValue = value
  for (const type of state.listTypes) {
    if (type.value == value) {
      type.class = 'typeSelected'
    } else {
      type.class = 'typeNormal'
    }
  }
}

//新增弹框时确定选中了一个列表类型事件
const pickListType = () => {
  const type = state.newTypeValue
  state.dialogVisible = false
  if (type == 0) {
    push({
      name: 'ListEdit',
      query: {
        id: null
      }
    })
  } else {
    ElMessage.warning('该类型列表还没开发完成，敬请期待！')
  }
}

/**
 * @description  定义列表刷新事件
 */
useEmitt({
  //刷新列表事件
  name: 'refreshDataViewList',
  callback: (type: string) => {
    if (type === 'add') {
      state.queryBody.pageNo = 1
    }
    handleSearch()
  }
})

// 搜索
const handleSearch = () => {
  state.queryBody.key = state.searchKey
  init()
}

//重置查询
const resetSearch = () => {
  state.searchKey = ''
  state.queryBody.params['Q_d.module_id_S_IN'] = ''
  handleSearch()
}
//点击模块树节点
const handleNodeClick = (data) => {
  state.queryBody.params['Q_d.module_id_S_IN'] = data
  state.curModuleId = data.split(',')[0]
  handleSearch()
}

//渲染页面的接口
const init = async () => {
  appStore.setFooter(false)
  state.tableView = []
  await queryDataList(state.queryBody)
    .then((res) => {
      const result = res as any
      var data = result.result.data
      state.tableView = data
      state.totalCount = result.result.totalCount
    })
    .catch(() => {})
}
</script>
<template>
  <div>
    <!-- 搜索條件卡片 -->
    <el-card class="box-card">
      <el-row :gutter="10" style="padding: 5px 5px; line-height: 28px" align="middle">
        <el-col :sm="5" :md="4" style="text-align: right">{{ $t('common.searchKey') }}</el-col>
        <el-col :sm="19" :md="12" style="text-align: left">
          <el-input
            v-model="state.searchKey"
            @keyup.enter="handleSearch"
            :placeholder="$t('common.inputText') + $t('dataList.name') + '/' + $t('common.remark')"
          />
        </el-col>
        <el-col :sm="24" :md="8" style="text-align: right">
          <div style="margin-right: -5px">
            <el-button @click="handleSearch" type="primary" size="small" plain
              ><Icon icon="ic:outline-search" /><span>{{ $t('common.query') }}</span></el-button
            >
            <el-button @click="resetSearch" type="info" size="small" plain>
              <Icon icon="icon-park-solid:clear-format" /><span>{{
                $t('common.reset')
              }}</span></el-button
            >
            <el-button type="success" size="small" plain @click="state.dialogVisible = true">
              <Icon icon="material-symbols:add-circle-rounded" /><span>{{ $t('common.add') }}</span>
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-container class="mainArea">
      <el-aside width="200px">
        <ModuleTree @node-click="handleNodeClick" />
      </el-aside>
      <el-main class="formcard">
        <!-- 搜索結果表格 -->
        <el-table
          :data="state.tableView"
          tooltip-effect="light"
          style="width: 100%; border: 1px solid #ddd; font-size: 12px"
          stripe
          row-key="id"
          default-expand-all
          :header-cell-style="{
            background: 'var(--el-color-primary-light-9)',
            color: '#409eff'
          }"
        >
          <el-table-column type="index" min-width="60">
            <template #header>
              <div style="margin-bottom: -10px">
                <Icon
                  icon="ant-design:field-number-outlined"
                  size="24"
                  :title="$t('common.number')"
              /></div>
            </template>
          </el-table-column>
          <el-table-column
            :prop="state.dataListField"
            :label="$t('dataList.name')"
            show-overflow-tooltip
            min-width="100"
          />
          <el-table-column prop="listType" :label="$t('dataList.type')" min-width="80">
            <template #default="{ row }">
              {{ $t('dataList.type' + row.listType) }}
            </template>
          </el-table-column>
          <el-table-column
            :prop="state.modNameField"
            :label="$t('orderNo.module')"
            min-width="110"
          />
          <el-table-column
            prop="mainTableName"
            :label="$t('dataList.mainTableName')"
            min-width="100"
          />
          <el-table-column
            prop="isLazy"
            :label="$t('dataList.isLazy')"
            min-width="70"
            align="center"
          >
            <template #default="{ row }">
              <span v-if="row.isLazy == 1">{{ $t('common.yes') }}</span>
              <span v-else>{{ $t('common.no') }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="pageSize"
            :label="$t('dataList.pageSize')"
            min-width="90"
            align="center"
          />
          <el-table-column prop="ver" :label="$t('form.ver')" min-width="70" />
          <el-table-column prop="status" :label="$t('common.status')" min-width="70" align="center">
            <template #default="{ row }">
              <span v-if="row.status == 0">{{ $t('entity.status0') }}</span>
              <span v-else>{{ $t('entity.status1') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="updateBy" :label="$t('common.updateBy')" min-width="86" />
          <el-table-column prop="updateTime" :label="$t('common.updateTime')" min-width="140" />
          <el-table-column fixed="right" :label="$t('common.operation')" width="160" align="center">
            <template #default="{ row }">
              <el-button
                type="primary"
                plain
                circle
                size="small"
                :title="$t('common.modify')"
                @click="edit(row.id, row.listType)"
              >
                <el-icon>
                  <Edit />
                </el-icon>
              </el-button>
              <el-button
                type="success"
                plain
                circle
                size="small"
                v-show="row.status == 1"
                :title="$t('dataList.preview')"
                @click="preview(row.id)"
              >
                <Icon icon="icon-park-outline:preview-open" />
              </el-button>
              <el-button
                type="danger"
                plain
                circle
                size="small"
                :title="$t('common.delete')"
                v-if="row.isBuildIn != 1"
                @click="deleteOne(row)"
              >
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
              <el-button
                type="success"
                plain
                circle
                size="small"
                v-show="row.status == 1"
                :title="$t('dataList.addMenu')"
                @click="add2Menu(row)"
              >
                <Icon icon="ic:sharp-menu-open" />
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分頁器 -->
        <div class="demo-pagination-block"
          ><el-pagination
            v-model:currentPage="state.queryBody.pageNo"
            v-model:page-size="state.queryBody.pageSize"
            @current-change="changePage"
            @size-change="changePageSize"
            :page-sizes="state.pageSizes"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="state.totalCount"
        /></div>
      </el-main>
    </el-container>

    <!-- 新增列表對話框 -->
    <el-dialog
      v-model="state.dialogVisible"
      :title="$t('dataList.addNew')"
      width="1000px"
      draggable
    >
      <el-row :gutter="20" style="margin: -20px -10px">
        <el-col :span="8" v-for="item in state.listTypes" :key="'Item' + item.value">
          <div :class="item.class" @click="clickListType(item.value)">
            <el-row :gutter="10">
              <el-col :span="8">
                <Icon :icon="item.icon" size="48" class="typeIcon" />
              </el-col>
              <el-col :span="16">
                <div class="typeTitle"> {{ $t('dataList.type' + item.value) }}</div>
                <div class="typeDesc">　　{{ $t('dataList.typeDesc' + item.value) }}</div>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer" style="text-align: center">
          <el-button type="primary" @click="pickListType">
            <el-icon><Check /></el-icon>&nbsp;{{ $t('common.ok') }}</el-button
          >
          <el-button @click="state.dialogVisible = false">
            <el-icon> <Close /> </el-icon>&nbsp;{{ $t('common.cancel') }}</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="less" scoped>
:deep(.el-card__header) {
  border-bottom: 0;
  box-sizing: border-box;
}

:deep(.el-radio) {
  display: block;
  line-height: 28px;
  text-align: center;
  white-space: normal;
  margin-right: 0;
}

.typeNormal {
  width: 100%;
  height: 140px;
  margin-top: 10px;
  background-color: #f5f5f5;
  border: 1px dotted #ddd;
}
div.typeNormal:hover {
  background-color: #feece2;
}

.typeSelected {
  width: 100%;
  height: 140px;
  margin-top: 10px;
  background-color: #feece2;
  border: 2px double red;
}
.typeIcon {
  color: darkblue;
  margin: 60px 0 0 25px;
}
.typeTitle {
  font-size: 18px;
  font-weight: bold;
  letter-spacing: 2px;
  margin: 10px 0 0 20px;
}
.typeDesc {
  font-size: 14px;
  margin: 5px 10px 5px -35px;
}
:deep(.el-select .el-option .el-input .el-select-dropdown__item) {
  font-size: 12px;
}

:deep(.el-input__inner) {
  &::placeholder {
    font-size: 12px;
  }
  font-size: 12px;
}

:deep(.v-footer) {
  height: 0px;
}
.mainArea {
  height: calc(100vh - 145px);
  overflow-x: hidden;
}
.formcard {
  margin: -12px -19px 0 -15px;
}
// 分頁器樣式
.demo-pagination-block {
  display: flex;
  justify-content: center;
  justify-items: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
:deep(.el-pagination__sizes > .el-select) {
  margin-top: -3px;
}
:deep(.el-pager li) {
  font-size: 12px;
  height: 28px;
  margin-top: -1px;
}
:deep(.el-pagination span:not([class*='suffix'])) {
  font-size: 12px;
}
</style>
